#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

int get_listen_fd(char*);
void* func(void*);

int main(int argc,char* argv[])
{
  int tcp_fd = get_listen_fd(argv[1]);

  struct sockaddr_in client;
  socklen_t len;
  int con_fd;
  pthread_t tid;
  printf("process wait\n");
  while(1)
  {
    con_fd = accept(tcp_fd,(struct sockaddr*)&client,&len);

    printf("%s,%hu\n",inet_ntoa(client.sin_addr),ntohs(client.sin_port));

    if(con_fd < 0)
    {
      perror("accept fail");
      return -1;
    }

    pthread_create(&tid,NULL,func,(void*)&con_fd);
  }


  return 0;
}

int get_listen_fd(char* port)
{
  int tcp_fd = socket(AF_INET,SOCK_STREAM,0);
  if(tcp_fd < 0)
  {
    perror("socket fail");
    exit(-1);
  }
  
  struct sockaddr_in server_addr;
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(atoi(port));
  inet_pton(AF_INET,"0.0.0.0",&server_addr.sin_addr);

  int ret = bind(tcp_fd,(struct sockaddr*)&server_addr,sizeof(server_addr));

  listen(tcp_fd,1);

  return tcp_fd;
}

void* func(void* fd)
{
  int tcp_fd = *(int*)fd;
  char buf[1024];
  while(1)
  {
    read(tcp_fd,buf,1024);
    printf("read is %s\n",buf);
  }
}
